﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using MMOShared;

namespace MMOMasterServer
{
    class Program
    {
        private static MasterServerDB _db;
        private static MasterVersionList _versions;

        private static readonly int _listenPort = 9876;

        static void Main(string[] args)
        {
            if(args.Length != 4) { 
                Console.WriteLine("Error: missing command line arguments.\nRemember server must be called like this:\n\n"+
                    "MMOMasterServer.exe [db server address] [database name] [database user] [database pass]");
                return;
            }

            Console.WriteLine("==================\nMaster Server Started...\n==================");
            
            //Startup database connection
            _db = new MasterServerDB(args[0],args[1],args[2],args[3]);
            Console.WriteLine("Connected to mySQL db");

            //Load versions
            _versions = new MasterVersionList();
            _versions.ScanDirectory("Updates\\");
            
            //Start listening on given port
            TcpListener listen = new TcpListener(_listenPort);
            listen.Start();
            Console.WriteLine("Server listening on port " + _listenPort);

            //Wait for new connections
            while(true){
                if(listen.Pending()){
                    TcpClient c = listen.AcceptTcpClient();
                    Console.WriteLine("New connection, creating connector thread");
                    Thread t = new Thread(() => LoginAcceptor.ProcessLogin(c,_db,_versions));
                    //Admit new connection in new thread
                    t.Start();
                }
            }
        }
    }
}
